<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';
import { LOGIN_APP } from '/@/api/modules/base/app-sys-user';
import {
  getCurrentInstance,
  showLoading,
  navigateBack,
  showToast,
  navigateTo,
  showModal,
  hideLoading,
  downloadFile,
  reLaunch,
  redirectTo,
} from '@tarojs/taro';
import { APPROVE_STATUE, APPROVE_STATUE_COLOR, APPROVE_STATUE_BG_COLOR } from '/@/common/constant';
import { state } from './state';
import ApproveList from './components/approve-list/approve-list.vue';
import ApprovePopup from './components/approve-popup/approve-popup.vue';
import ApproveEditForm from '../../approve/edit/components/approve-edit-form/approve-edit-form.vue';
import {
  QUERY_APP_FLOW_PATH_RECORD_DETAIL,
  CANCEL_APP_FLOW_PATH_RECORD,
  QUERY_APP_FLOW_PATH_RECORD_LIST,
} from '/@/api/modules/flow-path/flow-path';
import {
  setExtendAttributes,
  setDefaultExtendAttributes,
  findExtendAttributes,
  addFirstNode,
  isUserHandled,
  isCurrentUserApprove,
  isUserCopy,
  isDingTalkPCOrBrowser,
  isDingTalk,
} from './approve-detail';
import { Right as AppNutIconRight } from '@nutui/icons-vue-taro';
import MY_APPROVE_DETAIL_HISTORY from '/@/assets/image/icon/my-approve-detail-history.png';
import APPROVE_AGREE from '/@/assets/image/icon/approve_agree.png';
import APPROVE_REFUSE from '/@/assets/image/icon/approve_refuse.png';
import APPROVE_CANCEL from '/@/assets/image/icon/approve_cancel.png';
import ApproveDownloadButton from './components/approve-download-button.vue';
import ApproveShareButton from './components/approve-share-button.vue';
import ApproveRestartButton from './components/approve-restart-button.vue';
import dd from 'gdt-jsapi'; // 按需引入方法
import { cloneDeep, template } from 'lodash';
import { SuccessResult } from 'gdt-jsapi/invoker';
import { CAR_APPROVE_TEMPLATE_CODE, STORE_ROOM_APPROVE_TEMPLATE_CODE } from '/@/common/constant';
import { APP_MENU_TREE } from '/@/api/modules/base/app-menu';
/**
 *状态（1-审批中，2-已通过，3-已拒绝，4-已撤销）
 */
const APPROVE_STATUS_IMG = {
  1: '',
  2: APPROVE_AGREE,
  3: APPROVE_REFUSE,
  4: APPROVE_CANCEL,
};
/**
 * @description 当前路由信息
 *
 */
const params = getCurrentInstance().router?.params as {
  /**
   * 审批id
   */
  id: string;
  /**
   * 不同业务模块分两种：
   * send 发起审批的人,有撤销权限
   *
   */
  from?: string;
};

function getMyHandleStatus(isSelfApprove: boolean) {
  /**
   * 我的审批状态（1-待处理，2-已处理，4-已收到-抄送人, 3-历史记录）
   */
  let myHandleStatus: string | undefined = undefined;
  //发起人是自己，有可能审批人也是自己,要根据from参数判断
  if (params.from === 'send' && state.sourceRecord?.releaseUserId === state.uaaUserId) {
    // 3-历史记录
    myHandleStatus = '3';
  } else if (isSelfApprove) {
    //1-待处理
    myHandleStatus = '1';
  } else if (isUserHandled()) {
    //2-已处理
    myHandleStatus = '2';
  } else if (isUserCopy()) {
    //4-已收到-抄送人
    myHandleStatus = '4';
  }
  return myHandleStatus;
}

/**
 * @function 获取审批详情
 */
function getDetail(id?: string) {
  //url地址传入或者 自定跳转到下一条
  const newId = id ? id : params.id;
  showLoading();
  QUERY_APP_FLOW_PATH_RECORD_DETAIL({ id: newId }).then((res) => {
    state.record = res.flowpathRecordDto;
    state.sourceRecord = cloneDeep(state.record);
    state.attributes = res.flowpathRecordDto?.attributes;
    state.approvers = res.flowpathRecordDto?.approvers;
    state.currentMonthCount = res.currentMonthCount;

    //审批状态在审批中且审批人是自己
    const CurrentUserApprove = isCurrentUserApprove(state.uaaUserId);
    //是否能审批
    state.isApprove = CurrentUserApprove.approve;
    //提交的时候需要的参数
    approveState.approveId = CurrentUserApprove.id || '';
    const myHandleStatus = getMyHandleStatus(CurrentUserApprove.approve);
    if (myHandleStatus) {
      const attributeCfgList = findExtendAttributes(myHandleStatus);
      console.log('attributeCfgList', attributeCfgList);
      //属性配置个数和属性个数要相等
      if (
        attributeCfgList &&
        attributeCfgList.length > 0 &&
        attributeCfgList.length === state.attributes?.length
      ) {
        setExtendAttributes(attributeCfgList, myHandleStatus);
      } else {
        setDefaultExtendAttributes();
      }
    } else {
      setDefaultExtendAttributes();
    }
    //添加第一个节点数据
    addFirstNode(
      res.flowpathRecordDto?.releaseUserName,
      res.flowpathRecordDto?.releaseTime,
      res.flowpathRecordDto?.releaseUserPhone,
    );
  });
}

function cancel() {
  showModal({
    title: '审批撤销',
    content: '您确定审批撤销吗？',
    success: function (response) {
      if (response.confirm) {
        cancelHandle();
      }
    },
  });
}
/**
 *撤销
 */
function cancelHandle() {
  showLoading();
  CANCEL_APP_FLOW_PATH_RECORD({
    flowpathRecordDto: { id: state.record?.id },
  }).then((res) => {
    if (res.comResp?.code === 100) {
      navigateBack();
    }
  });
}

onMounted(() => {
  LOGIN_APP().then((res) => {
    state.uaaUserId = res.sysUserDto.uaaUserId || '';
    state.name = res.sysUserDto.name || '';
    getDetail();
  });
  APP_MENU_TREE({}).then((res) => {
    state.menuTree = res.dto || [];
  });
  //window 上挂在新方法
  window['completeApprovalDownload'] = (url: string) => {
    hideLoading();
    if (url) {
      if (downloadAndShare === 1) {
        completeApprovalDownload(url);
      } else if (downloadAndShare === 2) {
        shareFile(url);
      }
    } else {
      if (downloadAndShare === 1) {
        showToast({ title: '文件下载失败', icon: 'error' });
      } else if (downloadAndShare === 2) {
        showToast({ title: '分享文件失败', icon: 'error' });
      }
    }
  };
});

const approveState = reactive<{
  /**
   * agree/refuse
   */
  status: 'agree' | 'refuse';
  visible: boolean;
  approveId: string;
}>({
  status: 'agree',
  visible: false,
  approveId: '',
});

/**
 * 同意
 */
function agree() {
  const errorAttributeItem = state.attributes?.find((item) => {
    //可编辑/默认可编辑-属性为value空的情况
    //必须字段才有必要验证
    return (
      (!item.editAble || item.editAble === 1) &&
      item.attributeRequired === 1 &&
      !item.attributeValue
    );
  });
  //校验可编辑字段-属性value不能为空
  if (errorAttributeItem) {
    showToast({ title: `请填写${errorAttributeItem.attributeName}`, icon: 'error' });
    return;
  }
  approveState.status = 'agree';
  approveState.visible = true;
}
/**
 * 拒绝
 */
function refuse() {
  approveState.status = 'refuse';
  approveState.visible = true;
}

let isFirst = true;
/**
 * 刷新当前页面
 *
 */
function refresh() {
  //第一次
  if (isFirst) {
    state.list = [];
    queryWaitHandleList();
    isFirst = false;
  } else {
    approvedNext();
  }
}

let currentItem;
/**
 * 审批下一条
 */
function approvedNext() {
  showToast({
    title: state.list.length === 0 ? '处理完成' : '进入下一条',
    icon: 'success',
    success: () => {
      setTimeout(() => {
        if (state.list.length > 0) {
          currentItem = state.list.pop();
          getDetail(currentItem?.id);
        } else {
          if (currentItem) {
            getDetail(currentItem?.id);
          } else {
            getDetail();
          }
        }
      }, 2000);
    },
    duration: 2000,
  });
}

const downTime = ref();
const downloadFileUrl = ref('');
/**
 * 都需要上传文件
 * download : 1
 * share: 2
 */
let downloadAndShare = 0;

/**
 * 上传审批文件
 */
function uploadApproveFile() {
  sessionStorage.APPROVAL = JSON.stringify(state.sourceRecord); // 以 sessionStorage 缓存来传数据 (前提是同域名)
  sessionStorage.USER = JSON.stringify({ name: state.name });
  downTime.value = Date.now();
  //开发环境 url = '/approval/download'
  //生产环境 url = '/mh/dingtalk/approval/download'
  downloadFileUrl.value =
    process.env.APP_ENV === 'production'
      ? '/mh/dingtalk/approval/app/download'
      : '/approval/app/download';
  console.log('downloadApproveFile===>', window.location.href);
  showLoading();
}

/**
 * 下载审批文件
 */
function downloadApproveFile() {
  downloadAndShare = 1;
  uploadApproveFile();
}

//完成审批下载下载
function completeApprovalDownload(url: string) {
  console.log('downloadApproveFile===>url==>', url);
  console.log('navigator.userAgent', navigator.userAgent);

  if (navigator.userAgent.includes('TaurusApp')) {
    dingTalkDownload(url);
  } else {
    otherDownload(url);
  }
}

//下载审批单：浙政钉移动端隐藏，移动端PC端展示（浙政钉下载控件)
function dingTalkDownload(url: string) {
  const fileName = url.substring(url.lastIndexOf('/') + 1);
  dd.downloadFile({ url, name: fileName })
    .then((res) => {
      console.log(res);
    })
    .catch((error) => {
      console.log(error);
    });
}

//浏览器展示（taro自带下载控件）
function otherDownload(url: string) {
  const fileName = url.substring(url.lastIndexOf('/') + 1);
  downloadFile({
    url,
    success: async function (res) {
      console.log('otherDownload downloadFile', res);
      const a = document.createElement('a');
      const fileBlob = await fetch(res.tempFilePath).then((r) => r.blob());
      const url = URL.createObjectURL(fileBlob);
      a.href = url;
      a.download = fileName;
      a.click();
    },
  });
}

//分享审批单：仅在浙政钉框架下（移动端、PC端）展示，在浏览器中隐藏
function shareFile(url: string) {
  const fileName = url.substring(url.lastIndexOf('/') + 1);
  dd.shareFileToMessage({ fileName, fileUrl: url })
    .then((res: SuccessResult) => {
      console.log('shareFileToMessage', res);
    })
    .catch((err) => {
      console.log(err);
      showToast({ title: '文件分享失败', icon: 'error' });
    });
}

function shareApproveFile() {
  downloadAndShare = 2;
  uploadApproveFile();
}

/**
 *@description 审批列表-待处理
 * @param page 当前页
 * @param pageSize -每页条数
 */
function queryWaitHandleList(page: number = 1, pageSize: number = 1000) {
  showLoading();
  QUERY_APP_FLOW_PATH_RECORD_LIST({
    comQuery: { page, pageSize },
    myHandleStatus: '1',
  })
    .then((res) => {
      if (!res.flowpathRecordDto || !res.flowpathRecordDto.length) return;
      state.list.push(...res.flowpathRecordDto);
    })
    .then(() => {
      approvedNext();
    });
}

/**
 * 重新发起审批
 */
function createApprove() {
  //templateCode 固定
  const templateCode = state.record?.templateCode;
  if (!templateCode) {
    return;
  }
  const id = state.record?.id;
  const templateId = state.record?.templateId;
  if (templateCode === CAR_APPROVE_TEMPLATE_CODE) {
    //1. 用车审批 /pages/car-apply/index/index
    // navigateBack({
    //   delta: 2,
    //   success: (res) => {},
    // });
    redirectTo({
      url: `/pages/car-apply/index/index?id=${id}`,
    });
  } else if (templateCode === STORE_ROOM_APPROVE_TEMPLATE_CODE) {
    //2. 库房领用审批 /pages/police-security/store-room/index
    reLaunch({
      url: `/pages/police-security/store-room/index?id=${id}`,
    });
  } else {
    const menuItem = templateCodeFindByMenuTree(templateCode);
    if (menuItem) {
      //templateCode 在menu路径中的
      //1. 通用审批 /pages/custom-approve-single/edit/index
      //2. 物品领用模块 /pages/police-security/item-receive-custom/index
      //3. 报事报修模块 /pages/police-security/repair/edit-single/index
      reLaunch({
        url: `${menuItem.forword}&id=${id}`,
      });
    } else {
      //templateCode 在审批列表中
      //1. 发起审批 /pages/approve/edit/index
      //2. 警保业务 不考虑  /pages/police-security/
      reLaunch({
        url: `/pages/approve/edit/index?id=${templateId}&approvedId=${id}`,
      });
    }
  }
}

function templateCodeFindByMenuTree(templateCode: string) {
  //没有递归遍历，只从children中查询forword
  const childrenMenu: AppMenu.Dto[] = [];
  state.menuTree.forEach((item) => childrenMenu.push(...item.children));
  console.log('childrenMenu', childrenMenu);
  const menuItem = childrenMenu.find((item) => item.forword.includes(templateCode));
  return menuItem;
}
</script>

<template>
  <view class="my-approve-detail app-page--1">
    <app-navbar title="审批详情" />
    <scroll-view class="app-page__wrapper" :scroll-y="true" :lower-threshold="100">
      <view class="my-approve-detail__wrapper">
        <view class="my-approve-detail__approve-head">
          <image
            :src="APPROVE_STATUS_IMG[state.record?.status || 1]"
            class="my-approve-detail__approve-status-img"
          />
          <nut-cell-group>
            <nut-cell>
              <template v-slot:title>
                <view class="my-approve-detail__module-title-wrapper">
                  <text class="my-approve-detail__module-title">{{
                    state.record?.title || '-'
                  }}</text>
                </view>
                <view>
                  <text>{{ state.record?.organizationName }}</text>
                </view>
                <view>
                  <text>审批编号:&nbsp;&nbsp;{{ state.record?.recordCode }}</text>
                </view>
              </template>
              <template v-slot:link>
                <view>
                  <text
                    class="my-approve-detail__status"
                    :style="{
                      color: state.record?.status
                        ? APPROVE_STATUE_COLOR[state.record?.status]
                        : '#999',
                      backgroundColor: state.record?.status
                        ? APPROVE_STATUE_BG_COLOR[state.record?.status]
                        : '#999',
                    }"
                  >
                    <text>{{
                      state.record?.status ? APPROVE_STATUE[state.record?.status] : '-'
                    }}</text>
                  </text>
                </view>
              </template>
            </nut-cell>

            <approve-edit-form
              v-if="state.attributes && state.attributes.length > 0"
              :attributes="state.attributes"
            />
          </nut-cell-group>
        </view>
        <nut-cell-group>
          <nut-cell>
            <template v-slot:title>
              <text class="my-approve-detail__module-title">审批流程</text>
            </template>
          </nut-cell>
          <nut-cell>
            <approve-list
              :title="state.record?.title || '-'"
              :record-id="state.record?.id || ''"
              :sender-id="state.record?.releaseUserId || ''"
              :list="state.record?.approvers"
              :is-sender="params.from === 'send'"
            />
          </nut-cell>
        </nut-cell-group>
        <nut-cell-group>
          <nut-cell
            :title="`本月${state.record?.title || '-'}${state.currentMonthCount}次`"
            v-if="state.isApprove"
            @click="navigateTo({ url: `/pages/my-approve/history/index?id=${params.id}` })"
          >
            <template #icon>
              <image :src="MY_APPROVE_DETAIL_HISTORY" class="my-approve-detail__image" />
            </template>
            <template #link>
              <app-nut-icon-right />
            </template>
          </nut-cell>
        </nut-cell-group>
        <iframe
          v-if="downTime"
          style="width: 0; height: 0; border: 0"
          :key="downTime"
          :src="downloadFileUrl"
        ></iframe>
      </view>
    </scroll-view>
    <view
      class="my-approve-detail__footer"
      v-if="
        state.record?.canCancelStatus
          ?.split(',')
          .includes(state.record?.status?.toString() || '-1') && params.from === 'send'
      "
    >
      <approve-share-button @click="shareApproveFile()" v-if="isDingTalk()" />
      <approve-download-button @click="downloadApproveFile()" v-if="isDingTalkPCOrBrowser()" />

      <approve-restart-button @click="createApprove()" />
      <nut-button class="my-approve-detail__footer-btn" type="danger" @click="cancel()">
        撤销
      </nut-button>
    </view>
    <view class="my-approve-detail__footer" v-else-if="state.isApprove">
      <approve-share-button @click="shareApproveFile()" v-if="isDingTalk()" />
      <approve-download-button
        class="my-approve-detail__download"
        @click="downloadApproveFile()"
        v-if="isDingTalkPCOrBrowser()"
      />

      <nut-button class="my-approve-detail__footer-btn" type="info" @click="agree()"
        >同意</nut-button
      >
      <nut-button class="my-approve-detail__footer-btn" type="danger" @click="refuse()"
        >拒绝</nut-button
      >
      <approve-popup
        v-model="approveState.visible"
        :status="approveState.status"
        :is-signature="state.record?.isSignature"
        :approve-id="approveState.approveId"
        :attributes="state.attributes"
        @refresh="refresh()"
      />
    </view>

    <view class="my-approve-detail__footer" v-else>
      <approve-share-button @click="shareApproveFile()" v-if="isDingTalk()" />
      <approve-download-button @click="downloadApproveFile()" v-if="isDingTalkPCOrBrowser()" />
      <approve-restart-button @click="createApprove()" v-if="params.from === 'send'" />
    </view>
  </view>
</template>

<style lang="scss">
@import './index.scss';
</style>
